public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;
    //负载因子
    public double loadFactor=0.75;

    public HashBuck() {
        array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;
        Node cur = array[index];
        //1. 遍历当前链表,是否存在当前值
        while(cur!= null){
            if(cur.key ==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        //2.说明 没有当前值, 所以头插
        Node node= new Node(key,val);
        node.next=array[index];
        array[index]=node;
        usedSize++;

        //3.
        if(loadFactorCount()>= loadFactor){
            //当超过 负载因子时,要重新 哈希
            resize();
        }
    }
    //扩容 , 重新哈希
    private void resize(){
        Node[] newArray=new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur=array[i];//数组每一个节点 都是一条链表
            //开始遍历链表
            while(cur!= null){
                int newIndex=cur.key% newArray.length;
                //将数据 存放在 数组新的 newIndex 位置
                Node curN=cur.next;
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;
                cur=curN;
            }
        }
        array= newArray;
    }

    //计算负载因子
    private double loadFactorCount(){
        return usedSize*1.0 / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        //1. 遍历当前链表,是否存在当前值
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}